/**
 * include modules
 */
const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const serve = require('koa-static');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const log = require('./utils/logUtil');
const apiFormat = require('./middlewares/apiFormat');



/**
 * init connect Mongodb
 */



/**
 * include routings
 */
const api = require('./routes/api');

/**
 * error handler
 */
onerror(app);



/**
 * logger
 */
app.use(log());
app.use(logger());



/**
 *  use middlewares
 */

//添加格式化处理响应结果的中间件，在添加路由之前调用
app.use(apiFormat('^/api'));
app.use(bodyparser({
	enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(serve(__dirname + '/public'));
app.use(views(__dirname + '/views', {
	extension: 'pug'
}));


/**
 * session setting
 */


/**
 *  routing before validation session
 */
app.use(api.routes(), api.allowedMethods());


/**
 * check session
 */

/**
 * routing after validation session
 */


/**
 * error-handling
 */
app.on('error', (err, ctx) => {
	console.error('server error', err, ctx)
});

module.exports = app;
